package service

import (
	"github.com/shopspring/decimal"
	"shopping/dao/mysql"
	"shopping/model"
	"shopping/utils/pagination"
)

// ProductService 商品Service
type ProductService struct {
	productDao *mysql.ProductDao
}

// NewProductService 实例化
func NewProductService(dao *mysql.ProductDao) *ProductService {
	return &ProductService{
		productDao: dao,
	}
}

// GetAll 获取所有商品分页
func (service *ProductService) GetAll(page *pagination.Pages) *pagination.Pages {
	products, count, err := service.productDao.GetAll(page.Page, page.PageSize)
	if err != nil {
		return page
	}
	page.Items = products
	page.TotalCount = count
	return page
}

// CreateProduct 创建商品
func (service *ProductService) CreateProduct(name string, desc string, count int, price decimal.Decimal, cid int64) error {
	newProduct := model.NewProduct(name, desc, count, price, cid)
	return service.productDao.Create(newProduct)
}

// UpdateProduct 更新商品
func (service *ProductService) UpdateProduct(product *model.Product) error {
	return service.productDao.Update(*product)
}

// SearchProduct 查找商品
func (service *ProductService) SearchProduct(text string, page *pagination.Pages) *pagination.Pages {
	products, count := service.productDao.SearchByString(text, page.Page, page.PageSize)
	page.Items = products
	page.TotalCount = count
	return page
}
